package com.lscdu.gulimall.ruoyi_springboot.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.lscdu.gulimall.ruoyi_springboot.common.core.redis.RedisCache;
import com.lscdu.gulimall.ruoyi_springboot.service.ISysConfigService;
import com.lscdu.gulimall.ruoyi_springboot.utis.AjaxResult;
import com.lscdu.gulimall.ruoyi_springboot.utis.Base64;
import com.lscdu.gulimall.ruoyi_springboot.utis.constant.CacheConstants;
import com.lscdu.gulimall.ruoyi_springboot.utis.constant.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 啊昌
 * @date 2024/8/28 18:12
 * CaptchaController 验证码操作
 */
@RestController
public class CaptchaController {

	@Autowired
	private ISysConfigService configService;

	@Resource(name = "captchaProducerMath")
	DefaultKaptcha captchaProducerMath;

	@Value("${ruoyi.captchaType}")
	private String captchaType; //验证码类型 （数字）

	@Autowired
	private RedisCache redisCache;

	//生成验证码开关
	@GetMapping("/captchaImage")
	public AjaxResult getCode(HttpServletResponse response) throws IOException {
		AjaxResult ajaxResult = new AjaxResult();
		//1. 获取验证码开关
		boolean captchaEnabled = configService.selectCaptchaEnabled();
		ajaxResult.put("captchaEnabled", captchaEnabled);
		if(!captchaEnabled){
			return ajaxResult;
		}
		//2. 保存验证码信息
		String uuid = UUID.randomUUID().toString();
		// 存入redis的key
		String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
		String capStr = null, code = null;
		BufferedImage image = null;

		// 生成验证码
		String capText = captchaProducerMath.createText();
		capStr = capText.substring(0, capText.lastIndexOf("@"));
		code = capText.substring(capText.lastIndexOf("@") + 1);
		image= captchaProducerMath.createImage(capStr);

		redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
		// 转换流信息写出
		FastByteArrayOutputStream os = new FastByteArrayOutputStream();
		try {
			ImageIO.write(image, "jpg", os);
		} catch (IOException e) {
			return AjaxResult.error(e.getMessage());
		}

		ajaxResult.put("uuid", uuid);
		ajaxResult.put("img", Base64.encode(os.toByteArray()));
		return ajaxResult;
	}
}
